import React, { Component } from 'react'
import echarts from 'echarts'
import $ from 'jquery'
import {
    getPreviousDays,
    getTotalTime,
    formatJSON,
    getDateAndTime,
    setCookie,
    getCookie,
    delCookie,
    uuid,
} from '../util/util'
import {
    currentTemperatureOption,
    currentHumidityOption,
    currentDustOption,
    tempHumiTrendOption,
    dustTrendOption,
    currentYieldOption,
    currentActivationOption,
    currentPressureOption,
    yieldActTrendOption,
    outputTrendOption,
    forecastOption,
    machineParameterOption,
} from '../chart-option/option'
import '../../css/App.scss'

const equipmentStatusGantt = [
    {Create_Time: '09:00', Status: 0},
    {Create_Time: '10:00', Status: 1},
    {Create_Time: '11:28', Status: 3},
    {Create_Time: '12:00', Status: 2},
    {Create_Time: '13:30', Status: 1},
    {Create_Time: '15:55', Status: 0},
    {Create_Time: '17:27', Status: 3},
]

class App extends Component {

    state = {
        dateString: '',
        timeString: '',
        todayOutput: 125,// 今日产量
        currentNoise: 0,// 实时噪音
        todayElectricEnergy: 67,// 今日电能
        allElectricEnergy: 557,// 累计电能
        todayGasEnergy: 89,// 今日气能
        allGasEnergy: 637,// 累计气能
        idleTime: 0,// 累计闲置时间
        runningTime: 0,// 累计运行时间
        downTime: 0,// 累计宕机时间
        inactiveTime: 0,// 累计断网时间
        lamp1: '',// 六台设备的指示灯颜色
        lamp2: '',
        lamp3: '',
        lamp4: '',
        lamp5: '',
        lamp6: '',
        activation: 0,// 稼动率
        sequecneBkg: {// 时序联动图背景图片
            sequenceCustomerBkg: 'wait',
            sequence0Bkg: 'wait',
            sequence1Bkg: 'wait',
            sequence2Bkg: 'wait',
            sequence3Bkg: 'wait',
            sequence4Bkg: 'wait',
            sequence5Bkg: 'wait',
            sequence6Bkg: 'wait',
            sequence7Bkg: 'wait',
            sequence8Bkg: 'wait',
            sequence9Bkg: 'wait',
            sequenceLogisticsBkg: 'wait',
        },

        MWH_Cycle_Time: '13',// 半成品仓循环时间
        MWH_Robot_Speed: '60',// 半成品仓机械手速度
        Load_Cycle_Time: '5',// 上料循环时间
        Load_AGV_Speed: '10',// AGV速度
        Marking_Cycle_Time: '3',// 打标循环时间
        Checking_Cycle_Time: '3',// 检测循环时间
        Checking_Speed: '60',// 机械手速度
        Unload_Cycle_Time: '6',// 下料循环时间
        Unload_Speed: '60',// 机械手速度
        FWH_Cycle_Time: '5',// 成品仓循环时间
        FWH_Robot_Speed: '400',//

        IOT1ToWebApi: 'normal',// 生产应用-webapi
        IOT1ToService: 'normal',// 生产应用-Service
        IOT1ToWinApi: 'normal',// 生产应用-winapi
        IOT5ToWebApi: 'normal',// 集成组件-webapi
        IOT5ToService: 'normal',// 集成组件-Service
        IOT5ToWinApi: 'normal',// 集成组件-winapi
        IOT5ToIOT7: 'normal',
        IOT7ToIOT9: 'normal',
        IOT9To1: 'normal',
        IOT9To2: 'normal',
        IOT9To3: 'normal',
        IOT9To4: 'normal',
        IOT9To5: 'normal',
        IOT9To6: 'normal',

        equipmentStatusGantt : [],// 甘特图
        DOMArr: [],
        orderID: '3644266205',// 订单ID
        agvColor: '#fff',
        robotColor: '#fff',
        Marking_speed: '1.2',
        forecastDownTime: '17:00-17:45',
        forecastTime: '',
    }

    splitData (rawData) {
        let categoryData = [];
        let values = [];
        let newValues = [];
        for (let i = 0; i < rawData.length; i++) {
            categoryData.push(rawData[i].splice(0, 1)[0])
            values.push(rawData[i])
        }
        console.log(`values:${values}`)
        for (let item of values) {
            let a = item[0] + item[1];
            let b = [item[0], a, item[0], a];
            newValues.push(b);
            console.log(b)
        }
        console.log(`newValues:${newValues}`)
        return {
            categoryData: categoryData,
            values: newValues
        }
    }

    componentDidMount () {
        // 当前温度
        this.currentTemperatureChart = echarts.init(this.refs.temperature)
        this.currentTemperatureChart.setOption(currentTemperatureOption)
        // 当前湿度
        this.currentHumidityChart = echarts.init(this.refs.humidity)
        this.currentHumidityChart.setOption(currentHumidityOption)
        // 当前尘埃
        this.currentDustChart = echarts.init(this.refs.dust)
        this.currentDustChart.setOption(currentDustOption)
        // 温湿度趋势
        this.tempHumiTrendChart = echarts.init(this.refs.tempHumiTrend)
        this.tempHumiTrendChart.setOption(tempHumiTrendOption)
        // 尘埃趋势
        this.dustTrendChart = echarts.init(this.refs.dustTrend)
        this.dustTrendChart.setOption(dustTrendOption)
        // 当前良品率
        this.currentYieldChart = echarts.init(this.refs.yield)
        this.currentYieldChart.setOption(currentYieldOption)
        // 当前稼动率
        this.currentActivationChart = echarts.init(this.refs.activation)
        this.currentActivationChart.setOption(currentActivationOption)
        // 当前气压
        this.currentPressureChart = echarts.init(this.refs.pressure)
        this.currentPressureChart.setOption(currentPressureOption)
        // 良品率、稼动率趋势
        this.yieldActTrendChart = echarts.init(this.refs.yieldActTrend)
        this.yieldActTrendChart.setOption(yieldActTrendOption)
        // 产量趋势
        this.outputTrendChart = echarts.init(this.refs.outputTrend)
        this.outputTrendChart.setOption(outputTrendOption)
        // 预测结果呈现
        this.forecastChart = echarts.init(this.refs.forecast)
        this.forecastChart.setOption(forecastOption)
        // 电机气缸运行参数
        this.machineParameterChart = echarts.init(this.refs.machineParameter)
        this.machineParameterChart.setOption(machineParameterOption)

        /*// 获取实时的温度
        fetch('/api/mes/ReadCurrentTemperature')
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.currentTemperatureChart.setOption({
                    series: [{
                        name: '温度',
                        data: [{name: '温度', value: json.data}]
                    }]
                })
            })
            .catch((e) => {throw e})

        // 获取实时的湿度
        fetch('/api/mes/ReadCurrentDampness')
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.currentHumidityChart.setOption({
                    series: [{
                        name: '湿度',
                        data: [{name: '湿度', value: json.data}]
                    }]
                })
            })
            .catch((e) => {throw e})

        // 获取实时的尘埃
        fetch('/api/mes/ReadCurrentAriQuality')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.currentDustChart.setOption({
                    series: [{
                        name: '尘埃',
                        data: [{name: '尘埃', value: json.data}]
                    }]
                })
            })
            .catch((e) => {throw e})

        // 获取实时的气压
        fetch('/api/mes/ReadCurrentPressure')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.currentPressureChart.setOption({
                    series: [{
                        name: '气压',
                        data: [{name: '气压', value: json.data}]
                    }]
                })
            })
            .catch((e) => {throw e})

        // 获取实时的良品率
        fetch('/api/mes/ReadCurrentYeild')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.currentYieldChart.setOption({
                    series: [{
                        name: '良品率',
                        data: [{name: '良品率', value: json.data}]
                    }]
                })
            })
            .catch((e) => {throw e})

        // 获取当天的产量
        fetch('/api/mes/ReadCurrentOutput')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    todayOutput: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取当天的电能
        fetch('/api/mes/ReadTodayElectricEnergy')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    todayElectricEnergy: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取当天的气能
        fetch('/api/mes/ReadTodayGasEnergy')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    todayGasEnergy: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取实时的噪音
        fetch('/api/mes/ReadCurrentNoise')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    currentNoise: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取全部的电能
        fetch('/api/mes/GetAllElectricEnergy')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    allElectricEnergy: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取全部的气能
        fetch('/api/mes/GetAllGasEnergy')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    allGasEnergy: json.data
                })
            })
            .catch((e) => {throw e})*/

        // 获取整条生产线的状态，绘制甘特图
        fetch('/api/mes/GetTodayWholeEquipmentStatus')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    equipmentStatusGantt: json.data,
                });
            })
            .catch((e) => {throw e})

        /*const daysArr = getPreviousDays(15)
        // 获取近15天的良品率趋势（不包含当天）
        this.yieldActTrendChart.setOption({
            xAxis: [{data: daysArr}]
        })

        fetch('/api/mes/GetDaysYeild')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.yieldActTrendChart.setOption({
                    series: [{
                        name: '良品率',
                        data: json.data,
                    }],
                    xAxis: [{
                        data: daysArr,
                    }],
                })
            })
            .catch((e) => {throw e})

        // 获取近15天的产量趋势（不包含当天）
        this.outputTrendChart.setOption({
            xAxis: [{data: daysArr}]
        })
        fetch('/api/mes/GetDaysOutput')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.outputTrendChart.setOption({
                    series: [{
                        name: '产量',
                        data: json.data,
                    }],
                    xAxis: [{
                        data: daysArr,
                    }],
                })
            })
            .catch((e) => {throw e})

        // 发送当天稼动率给后端
        fetch('/api/mes/WriteUtilizationRate?InputJson={Date:"2018-01-03",Data:0.56}')
            .then((response) => {return response.json()})
            .then((json) => {

            })
            .catch((e) => {throw e})

        // 获取半成品仓循环时间
        fetch('/api/mes/ReadMWH_Cycle_Time')
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    MWH_Cycle_Time: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取半成品仓机械手速度
        fetch('/api/mes/ReadMWH_Robot_Speed')
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    MWH_Robot_Speed: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取上料循环时间
        fetch('/api/mes/ReadLoad_Cycle_Time')
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    Load_Cycle_Time: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取AGV速度
        fetch('/api/mes/ReadLoad_AGV_Speed')
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    Load_AGV_Speed: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取打标循环时间
        fetch('/api/mes/ReadMarking_Cycle_Time')
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    Marking_Cycle_Time: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取检测循环时间
        fetch('/api/mes/ReadChecking_Cycle_Time')
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    Checking_Cycle_Time: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取取像速度
        fetch('/api/mes/ReadChecking_Speed')
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    Checking_Speed: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取下料循环时间
        fetch('/api/mes/ReadUnload_Cycle_Time')
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    Unload_Cycle_Time: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取下料速度
        fetch('/api/mes/ReadUnload_Speed')
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    Unload_Speed: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取成品仓循环时间
        fetch('/api/mes/ReadFWH_Cycle_Time')
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    FWH_Cycle_Time: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取半成品仓机械手速度
        fetch('/api/mes/ReadFWH_Robot_Speed')
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    FWH_Robot_Speed: json.data
                })
            })
            .catch((e) => {throw e})*/

        // 获取预测结果呈现数据
        // let xAxisData = ['6','7','8','9','10','11','12','13','14','15','16','17','18',];
        /*$.ajax({
            url: '/TheWebService.asmx/GetForecast',
            type: 'GET',
            async: true,
            success: (response)=>{
                const XMLObj = response.getElementsByTagName('string')[0];
                const jsonStr = XMLObj.innerHTML;
                const json = JSON.parse(formatJSON(jsonStr));
                const actual = json.data.actual;
                const forecast = json.data.forecast;
                const data = this.splitData(json.data.rectangular);
                this.forecastChart.setOption({
                    xAxis: {
                        data: data.categoryData,
                    },
                    series: [{
                        name: '亲和度',
                        data: data.values,
                    }, {
                        name: '实际值',
                        data: actual,
                    }, {
                        name: '预测值',
                        data: forecast,
                    }]
                });
            },
            error: (e)=>{throw e}
        })*/

        let now = new Date()
        let timeInterval = 10 * 60 * 1000
        let dataLength = 10 * 60 / 2
        let startTime = new Date((now.getTime() - timeInterval))

        let temp = 25
        let humidity = 55
        let dust = 20
        let tempData = []
        let humiData = []
        let dustData = []
        let xAxisDataArr = []
        let endTimeMill = startTime.getTime()
        let machineEndTimeMill = startTime.getTime()
        let clock = 0
        let machineDataLength = 10 * 60 / 5
        let machineClock = 0
        let machinevVoltage = 380
        let machineCurrent = 4
        let machineTemp = 90
        let machineLoad = 50
        let machineVoltageData = []
        let machineCurrentData = []
        let machineTempData = []
        let machineLoadData = []
        let machineXAxisData = []

        // 生成随机的 温度、湿度、尘埃 数据
        function randomData () {
            endTimeMill = endTimeMill + 2000
            let a = new Date(endTimeMill)
            let hour = a.getHours() > 9 ? a.getHours() : `0${a.getHours()}`
            let minute = a.getMinutes() > 9 ? a.getMinutes() : `0${a.getMinutes()}`
            let second = a.getSeconds() > 9 ? a.getSeconds() : `0${a.getSeconds()}`

            temp = Math.round((temp + Math.random() * 6 - 3))
            humidity = Math.round((humidity + Math.random() * 6 - 3))
            dust = Math.round((dust + Math.random() * 10 - 5))
            if (temp > 30) {
                temp = 30
            } else if (temp < 20) {
                temp = 20
            }
            if (humidity > 70) {
                humidity = 70
            } else if (humidity < 40) {
                humidity = 40
            }
            if (dust > 30) {
                dust = 30
            } else if (dust < 10) {
                dust = 10
            }

            return {
                tempValue: temp,
                humiValue: humidity,
                xAxisData: [hour, minute].join(':'),
                dustValue: dust,
            }
        }

        // 生成随机的电机的参数
        function randomMachineData() {
            machineEndTimeMill = machineEndTimeMill + 5000
            let a = new Date(machineEndTimeMill)
            let hour = a.getHours() > 9 ? a.getHours() : `0${a.getHours()}`
            let minute = a.getMinutes() > 9 ? a.getMinutes() : `0${a.getMinutes()}`
            let second = a.getSeconds() > 9 ? a.getSeconds() : `0${a.getSeconds()}`

            machinevVoltage = Math.round((machinevVoltage + Math.random() * 20 - 10))
            machineCurrent = Math.round((machineCurrent + Math.random() * 2 - 1))
            machineTemp = Math.round((machineTemp + Math.random() * 20 - 10))
            machineLoad = Math.round((machineLoad + Math.random() * 20 - 10))
            if (machinevVoltage > 400) {
                machinevVoltage = 400
            } else if (machinevVoltage < 360) {
                machinevVoltage = 360
            }
            if (machineCurrent > 6) {
                machineCurrent = 6
            } else if (machineCurrent < 4) {
                machineCurrent = 4
            }
            if (machineTemp > 180) {
                machineTemp = 180
            } else if (machineTemp < 90) {
                machineTemp = 90
            }
            if (machineLoad > 80) {
                machineLoad = 80
            } else if (machineLoad < 30) {
                machineLoad = 30
            }

            return {
                machinevVoltage,
                machineCurrent,
                machineTemp,
                machineLoad,
                xAxisData: [hour, minute].join(':'),
            }
        }

        for (let i = 0; i < dataLength; i++) {
            let obj = randomData()
            tempData.push(obj.tempValue)
            humiData.push(obj.humiValue)
            xAxisDataArr.push(obj.xAxisData)
            dustData.push(obj.dustValue)
        }

        for (let i = 0; i < machineDataLength; i++) {
            let machineObj = randomMachineData()
            machineVoltageData.push(machineObj.machinevVoltage)
            machineCurrentData.push(machineObj.machineCurrent)
            machineTempData.push(machineObj.machineTemp)
            machineLoadData.push(machineObj.machineLoad)
            machineXAxisData.push(machineObj.xAxisData)
        }

        let orderIDFlag = true;

        // 定时器
        let tempHumiTrendInterval = setInterval(function fn() {
            clearInterval(tempHumiTrendInterval);

            // 设置时钟的时间
            const dateObj = getDateAndTime()
            this.setState({
                dateString: dateObj.date,
                timeString: dateObj.time,
            })

            // 如果判断到已经过了一天，则自动更新近15天趋势的X轴标签
            // 随机生成今日电能、今日气能，自动累加累计电能和累计气能
            let now = new Date();
            let year = now.getFullYear();
            let month = now.getMonth() + 1;
            month = month > 9 ? month : `0${month}`;
            let day = now.getDate();
            day = day > 9 ? day : `0${day}`;
            let hour = now.getHours();
            let minute = now.getMinutes();
            let dateStr = `${month}-${day}`;
            let currentDate = getCookie('currentDate');
            // 判断不是当天
            if (dateStr != currentDate) {
                const daysArr = getPreviousDays(15)
                // 获取近15天的良品率趋势（不包含当天）
                this.yieldActTrendChart.setOption({
                    xAxis: [{data: daysArr}]
                })
                this.outputTrendChart.setOption({
                    xAxis: [{data: daysArr}],
                })
                let todayElectricEnergy = Math.round(Math.random() * 50 + 50);
                let todayGasEnergy = Math.round(Math.random() * 50 + 50);
                let allElectricEnergy = getCookie('allElectricEnergy') || 0;
                let allGasEnergy = getCookie('allGasEnergy') || 0;
                allElectricEnergy = parseInt(allElectricEnergy) + todayElectricEnergy;
                allGasEnergy = parseInt(allGasEnergy) + todayGasEnergy;
                this.setState({
                    todayElectricEnergy,
                    todayGasEnergy,
                    allElectricEnergy,
                    allGasEnergy,
                });
                setCookie({currentDate: dateStr});
                setCookie({allElectricEnergy});
                setCookie({allGasEnergy});
                /*this.forecastChart.setOption({
                    title: {
                        text: `预测结果(${year}/${month}/${day})`
                    },
                });*/
                let previousDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);
                let previousYear = previousDate.getFullYear();
                let previousMonth = previousDate.getMonth() + 1;
                previousMonth = previousMonth > 9 ? previousMonth : `0${previousMonth}`;
                let previousDay = previousDate.getDate();
                let a = `预测结果(${previousYear}/${previousMonth}/${previousDay})`;
                this.setState({
                    forecastTime: `${previousYear}/${previousMonth}/${previousDay}`
                });
            }
            
            clock += 1
            machineClock += 1
            if (machineClock == 5) {
                machineClock = 0
                // if (hour < 17 || (hour == 17 && minute <= 30)) {
                    let obj = randomMachineData()
                    machineVoltageData.shift()
                    machineCurrentData.shift()
                    machineTempData.shift()
                    machineLoadData.shift()
                    machineXAxisData.shift()

                    machineVoltageData.push(obj.machinevVoltage)
                    machineCurrentData.push(obj.machineCurrent)
                    machineTempData.push(obj.machineTemp)
                    machineLoadData.push(obj.machineLoad)
                    machineXAxisData.push(obj.xAxisData)
                    this.machineParameterChart.setOption({
                        series: [{
                            name: '电压',
                            data: machineVoltageData,
                        }, {
                            name: '电流',
                            data: machineCurrentData,
                        }, {
                            name: '温度',
                            data: machineTempData,
                        }, {
                            name: '负载',
                            data: machineLoadData,
                        }],
                        xAxis: [{
                            data: machineXAxisData
                        }]
                    })
                // }
                
            }

            if (clock == 2) {
                clock = 0
                // if (hour < 17 || (hour == 17 && minute <= 30)) {
                    let obj = randomData()
                    tempData.shift()
                    xAxisDataArr.shift()
                    humiData.shift()
                    tempData.push(obj.tempValue)
                    xAxisDataArr.push(obj.xAxisData)
                    humiData.push(obj.humiValue)
                    this.tempHumiTrendChart.setOption({
                        series: [{
                            name: '温度',
                            data: tempData,
                        }, {
                            name: '湿度',
                            data: humiData,
                        }],
                        xAxis: [{
                            data: xAxisDataArr
                        }]
                    })
                    this.currentTemperatureChart.setOption({
                        series: [{
                            name: '温度',
                            data: [{name: '温度', value: obj.tempValue}]
                        }]
                    });
                    this.currentHumidityChart.setOption({
                        series: [{
                            name: '湿度',
                            data: [{name: '湿度', value: obj.humiValue}]
                        }]
                    });

                    dustData.shift()
                    dustData.push(obj.dustValue)
                    this.dustTrendChart.setOption({
                        series: [{
                            name: '尘埃',
                            data: dustData,
                        }],
                        xAxis: [{
                            data: xAxisDataArr
                        }]
                    })
                    this.currentDustChart.setOption({
                        series: [{
                            name: '尘埃',
                            data: [{name: '尘埃', value: obj.dustValue}]
                        }]
                    });
                // }
                
            }


            // 获取整条生产线的状态，绘制甘特图
            fetch('/api/mes/GetTodayWholeEquipmentStatus')
                .then((response) => {return response.json()})
                .then((json) => {
                    json = JSON.parse(formatJSON(json))

                    // 临时将Status修改为1，本来应该为0
                    const timeObj = this.getGantt(json.data, {Create_Time: '09:00', Status: 1});
                    const timeArr = getTotalTime(timeObj.periodArr);
                    const DOMArr = timeObj.DOMArr;
                    let idleTime = 0
                    let runningTime = 0
                    let downTime = 0
                    let inactiveTime = 0
                    for (let i of timeArr) {
                        switch (i.status) {
                            case 0:
                                idleTime = parseFloat(i.time.toFixed(2))
                                break
                            case 1:
                                runningTime = parseFloat(i.time.toFixed(2))
                                break
                            case 2:
                                downTime = parseFloat(i.time.toFixed(2))
                                break
                            case 3:
                                inactiveTime = parseFloat(i.time.toFixed(2))
                                break
                        }
                    }
                    let activation = runningTime / (idleTime + runningTime + downTime + inactiveTime)
                    activation = Math.round(activation * 100)
                    console.log(`稼动率:${activation}`)
                    this.setState({
                        idleTime,
                        runningTime,
                        downTime,
                        inactiveTime,
                        DOMArr,
                        equipmentStatusGantt: json.data,
                    })
                    this.currentActivationChart.setOption({
                        series: [{
                            name: '稼动率',
                            data: [{name: '稼动率', value: activation}]
                        }]
                    })

                })
                .catch((e) => {throw e})

            // 获取流程信息
            fetch('/api/mes/Status')
                .then((response) => {return response.json()})
                .then((json) => {
                    const order = parseInt(json);
                    let sequenceBkgArr = [];
                    let agvColor = '';
                    let robotColor = '';
                    for (let i = 0; i < 11; i++) {
                        if (i < order) {
                            sequenceBkgArr.push('idle')
                        } else if (i == order) {
                            sequenceBkgArr.push('running')
                        } else {
                            sequenceBkgArr.push('wait')
                        }
                    }
                    if (order < 5) {
                        agvColor = '#fff';
                    } else if (order == 5) {
                        agvColor = '#7fffaa';
                    } else if (order > 5) {
                        agvColor = '#fbff7f';
                    }
                    if (order < 8) {
                        robotColor = '#fff';
                    } else if (order == 8) {
                        robotColor = '#7fffaa';
                    } else if (order > 8) {
                        robotColor = '#fbff7f';
                    }
                    this.setState({
                        sequecneBkg: {
                            sequenceCustomerBkg: 'idle',
                            sequence0Bkg: sequenceBkgArr[0],
                            sequence1Bkg: sequenceBkgArr[1],
                            sequence2Bkg: sequenceBkgArr[2],
                            sequence3Bkg: sequenceBkgArr[3],
                            sequence4Bkg: sequenceBkgArr[4],
                            sequence5Bkg: sequenceBkgArr[5],
                            sequence6Bkg: sequenceBkgArr[6],
                            sequence7Bkg: sequenceBkgArr[7],
                            sequence8Bkg: sequenceBkgArr[8],
                            sequence9Bkg: sequenceBkgArr[9],
                            sequenceLogisticsBkg: sequenceBkgArr[10],
                        },
                        agvColor,
                        robotColor,
                    })
                    // 如果status为0则新生成一个订单ID
                    if (order == 0 && orderIDFlag === true) {
                        const orderID = uuid(10, 10);
                        this.setState({
                            orderID,
                        });
                        orderIDFlag = false;
                    }
                    if (order != 0) {
                        orderIDFlag = true;
                    }
                    
                })
                .catch((e) => {throw e})

            // 获取各个设备的状态
            for (let i = 1; i < 7; i++) {
                let url = `/api/mes/GetEquipment${i}Status`
                fetch(url)
                    .then((response) => {return response.json()})
                    .then((json) => {
                        let lampColor = {}
                        let lamp = ''
                        json = JSON.parse(formatJSON(json))
                        let data = parseInt(json.data)
                        switch (data) {
                            case 0:
                                lamp = '#fbff7f'
                                break
                            case 1:
                                lamp = '#7fffaa'
                                break
                            case 2:
                                lamp = '#ff4c76'
                                break
                        }
                        this.setState({
                            [`lamp${i}`]: lamp
                        })
                    })
                    .catch((e) => {throw e})
            }

            let forecastDownTimeStart = new Date(now.getTime() + 5 * 60 * 60 * 1000);
            let forecastHourStart =  forecastDownTimeStart.getHours();
            forecastHourStart = forecastHourStart > 9 ? forecastHourStart : `0${forecastHourStart}`;
            let forecastMinuteStart = forecastDownTimeStart.getMinutes();
            forecastMinuteStart = forecastMinuteStart > 9 ? forecastMinuteStart : `0${forecastMinuteStart}`;

            let forecastDownTimeEnd = new Date(now.getTime() + 6 * 60 * 60 * 1000);
            let forecastHourEnd =  forecastDownTimeEnd.getHours();
            forecastHourEnd = forecastHourEnd > 9 ? forecastHourEnd : `0${forecastHourEnd}`;
            let forecastMinuteEnd = forecastDownTimeEnd.getMinutes();
            forecastMinuteEnd = forecastMinuteEnd > 9 ? forecastMinuteEnd : `0${forecastMinuteEnd}`;

            let forecastDownTime = `${forecastHourStart}:00-${forecastHourEnd}:00`;
            this.setState({
                forecastDownTime
            });

            tempHumiTrendInterval = setInterval(fn.bind(this), 1000);
        }.bind(this), 1000);

        // 将当天的日期存入cookie，如果从cookie中读取的日期和实时获取的日期不一致，则说明不是同一天
        let year = now.getFullYear();
        let month = now.getMonth() + 1;
        month = month > 9 ? month : `0${month}`;
        let day = now.getDate();
        day = day > 9 ? day : `0${day}`;
        let dateStr = `${month}-${day}`;
        setCookie({currentDate: dateStr});

        const daysArr = getPreviousDays(15)
        // 获取近15天的良品率趋势（不包含当天）
        this.yieldActTrendChart.setOption({
            xAxis: [{data: daysArr}]
        })
        this.outputTrendChart.setOption({
            xAxis: [{data: daysArr}],
        })

        let allElectricEnergy = getCookie('allElectricEnergy') || 0;
        let allGasEnergy = getCookie('allGasEnergy') || 0;
        let todayElectricEnergy = Math.round(Math.random() * 50 + 50);
        let todayGasEnergy = Math.round(Math.random() * 50 + 50);
        allElectricEnergy = parseInt(allElectricEnergy) + todayElectricEnergy;
        allGasEnergy = parseInt(allGasEnergy) + todayGasEnergy;
        this.setState({
                    todayElectricEnergy,
                    todayGasEnergy,
                    allElectricEnergy,
                    allGasEnergy,
                });
        setCookie({allElectricEnergy});
        setCookie({allGasEnergy});

        /*let previousDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);
        let previousYear = previousDate.getFullYear();
        let previousMonth = previousDate.getMonth() + 1;
        previousMonth = previousMonth > 9 ? previousMonth : `0${previousMonth}`;
        let previousDay = previousDate.getDate();
        this.forecastChart.setOption({
            title: {
                text: `预测结果(${previousYear}/${previousMonth}/${previousDay})`
            },
        });*/
        let previousDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);
        let previousYear = previousDate.getFullYear();
        let previousMonth = previousDate.getMonth() + 1;
        previousMonth = previousMonth > 9 ? previousMonth : `0${previousMonth}`;
        let previousDay = previousDate.getDate();
        let a = `预测结果(${previousYear}/${previousMonth}/${previousDay})`;
        this.setState({
            forecastTime: `${previousYear}/${previousMonth}/${previousDay}`
        });
    }

    getGantt (timeArr, initValue) {
        let DOMArr = []
        let periodArr = []

        timeArr.reduce((returnedItem, nextItem) => {
            let timeStart = returnedItem.Create_Time
            let timeEnd = nextItem.Create_Time
            let arrStart = timeStart.split(':')
            let arrEnd = timeEnd.split(':')
            let secondStart = parseInt(arrStart[0]) * 60 * 60 + parseInt(arrStart[1] * 60)
            let secondEnd = parseInt(arrEnd[0] * 60 * 60 + parseInt(arrEnd[1] * 60))
            let second = secondEnd - secondStart
            let timeStr = (second / 3600).toFixed(3)
            let percent = second / 30600
            percent = `${percent * 100}%`
            let obj = {width: percent}
            switch (returnedItem.Status) {
                case 0:
                    obj.backgroundColor = '#fbff7f'
                    break
                case 1:
                    obj.backgroundColor = '#7fffaa'
                    break
                case 2:
                    obj.backgroundColor = '#ff4c76'
                    break
                case 3:
                    obj.backgroundColor = '#4f5e79'
                    break
            }
            DOMArr.push((<div style={{width: obj.width, backgroundColor: obj.backgroundColor}}></div>))
            periodArr.push({status: returnedItem.Status, time: timeStr})
            return nextItem
        }, initValue)

        return {DOMArr, periodArr}
    }

    render () {
        return (
            <div className="App">
                <div className="App-header">
                    <span className="date">{this.state.dateString}</span>
                    <span className="title">紫光云引擎智能工厂</span>
                    <span className="time">{this.state.timeString}</span>
                </div>
                <div className="App-content">
                    <div className="content-left">
                        <div className="content-left-tempHumiDust">
                            <div ref='temperature' className="temperature"></div>
                            <div ref='humidity' className="humidity"></div>
                            <div ref='dust' className="dust"></div>
                        </div>
                        <div className="left-center">
                            <div className="content-left-tempHumiTrend" ref='tempHumiTrend'></div>
                            <div className="content-left-dustTrend" ref="dustTrend"></div>
                            <div className="content-left-energy" ref='energy'>
                                <div className="energy .flex-column-center">
                                    <div className="energy-title">今日电能</div>
                                    <div className="energy-data">{this.state.todayElectricEnergy}</div>
                                </div>
                                <div className="energy">
                                    <div className="energy-title">累计电能</div>
                                    <div className="energy-data">{this.state.allElectricEnergy}</div>
                                </div>
                                <div className="energy">
                                    <div className="energy-title">今日气能</div>
                                    <div className="energy-data">{this.state.todayGasEnergy}</div>
                                </div>
                                <div className="energy">
                                    <div className="energy-title">累计气能</div>
                                    <div className="energy-data">{this.state.allGasEnergy}</div>
                                </div>
                            </div>
                        </div>
                        <div className="left-down">
                            <div className="content-left-lineStatus">
                                <div className="lineStatus-title">设备运转状态</div>
                                <div className="lineStatus-guide">
                                    <span><i className="idle"></i>闲置</span>
                                    <span><i className="running"></i>运行</span>
                                    <span><i className="down"></i>宕机</span>
                                </div>
                                <div className="lineStatus-gantt">
                                    <div className="dashed-line"></div>
                                    <div className="gantt">
                                        {this.state.DOMArr}
                                    </div>
                                </div>
                                <div className="lineStatus-time">
                                    <div>累计运行：<span className="running">{this.state.runningTime}</span>小时</div>
                                    <div>累计闲置：<span className="idle">{this.state.idleTime}</span>小时</div>
                                    <div>累计宕机：<span className="down">{this.state.downTime}</span>小时</div>
                                </div>
                            </div>
                            <div className="content-left-equipmentStatus">
                                <div className="orderID">订单ID：<span>{this.state.orderID}</span></div>
                                <div className="equipment-content">
                                    <div style={{width: '90%'}}>
                                        <div className="equipmentStatus">
                                            <div className="equipment">
                                                <img src="../images/material.png" className="equipment-img material"/>
                                                <div className="equipment-lamp"
                                                     style={{backgroundColor: this.state.lamp1}}></div>
                                                <div className="equipment-info">
                                                    <div>Cycle Time：<span>{this.state.MWH_Cycle_Time}</span>秒</div>
                                                    {/*<div>储位ID：<span>11212</span></div>*/}
                                                    <div>机械手速度：<span>{this.state.MWH_Robot_Speed}</span>r/min</div>
                                                </div>
                                            </div>
                                            <div className="equipment-status-right"></div>
                                            <div className="equipment">
                                                <img src="../images/supply.png" className="equipment-img supply"/>
                                                <div className="equipment-lamp"
                                                     style={{backgroundColor: this.state.lamp2}}></div>
                                                <div className="equipment-info">
                                                    <div>Cycle Time：<span>{this.state.Load_Cycle_Time}</span>秒</div>
                                                    <div>AGV速度：<span>{this.state.Load_AGV_Speed}</span>m/min</div>
                                                    {/*<div>CCD门槛值：<span>50</span></div>*/}
                                                    {/*<div>取像速度：<span>50</span></div>*/}
                                                </div>
                                            </div>
                                            <div className="equipment-status-right"></div>
                                            <div className="equipment">
                                                <img src="../images/marking.png" className="equipment-img marking"/>
                                                <div className="equipment-lamp"
                                                     style={{backgroundColor: this.state.lamp3}}></div>
                                                <div className="equipment-info">
                                                    <div>Cycle Time：<span>{this.state.Marking_Cycle_Time}</span>秒</div>
                                                    <div>打标速度：<span>{this.state.Marking_speed}</span>s</div>
                                                    {/*<div>打标头速度：<span>11212</span></div>*/}
                                                    {/*<div>中心位置：<span>50</span></div>*/}
                                                </div>
                                            </div>
                                        </div>
                                        <div className="equipmentStatus">
                                            <div className="equipment">
                                                <img src="../images/check.png" className="equipment-img check"/>
                                                <div className="equipment-lamp"
                                                     style={{backgroundColor: this.state.lamp6}}></div>
                                                <div className="equipment-info">
                                                    <div>Cycle Time：<span>{this.state.Checking_Cycle_Time}</span>秒</div>
                                                    {/*<div>CCD门槛值：<span>11212</span></div>*/}
                                                    {/*<div>取像位置：<span>50</span></div>*/}
                                                    <div>取像速度：<span>{this.state.Checking_Speed}</span>ms</div>
                                                </div>
                                            </div>
                                            <div className="equipment-status-left"></div>
                                            <div className="equipment">
                                                <img src="../images/laying-off.png" className="equipment-img laying-off"/>
                                                <div className="equipment-lamp"
                                                     style={{backgroundColor: this.state.lamp5}}></div>
                                                <div className="equipment-info">
                                                    <div>Cycle Time：<span>{this.state.Unload_Cycle_Time}</span>秒</div>
                                                    {/*<div>皮带速度：<span>11212</span></div>*/}
                                                    <div>机械手速度：<span>{this.state.Unload_Speed}</span>r/min</div>
                                                </div>
                                            </div>
                                            <div className="equipment-status-left"></div>
                                            <div className="equipment">
                                                <img src="../images/product.png" className="equipment-img product"/>
                                                <div className="equipment-lamp"
                                                     style={{backgroundColor: this.state.lamp4}}></div>
                                                <div className="equipment-info">
                                                    <div>Cycle Time：<span>{this.state.FWH_Cycle_Time}</span>秒</div>
                                                    {/*<div>储位ID：<span>11212</span></div>*/}
                                                    <div>机械手速度：<span>{this.state.FWH_Robot_Speed}</span>r/min</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="equipment-status-down"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="content-center">
                        <div className="center-up">
                            <div className="linkageMap-title">
                                时序联动图
                                <div className="linkageMap-title-guide guide-right">
                                    <div><i className="idle"></i>执行完成</div>
                                    <div><i className="running"></i>正在执行</div>
                                    <div><i className="wait"></i>未执行</div>
                                    <div><i className="down"></i>异常</div>
                                </div>
                            </div>
                            <div className="linkageMap-content">
                                <img src={`../images/linkageMap/c-${this.state.sequecneBkg.sequenceCustomerBkg}.png`} />
                                <img src={`../images/linkageMap/0-${this.state.sequecneBkg.sequence0Bkg}.png`} />
                                <img src={`../images/linkageMap/1-${this.state.sequecneBkg.sequence1Bkg}.png`} />
                                <img src={`../images/linkageMap/2-${this.state.sequecneBkg.sequence2Bkg}.png`} />
                                <img src={`../images/linkageMap/3-${this.state.sequecneBkg.sequence3Bkg}.png`} />
                                <img src={`../images/linkageMap/4-${this.state.sequecneBkg.sequence4Bkg}.png`} />
                                <img src={`../images/linkageMap/5-${this.state.sequecneBkg.sequence5Bkg}-2.png`} />
                                <img src={`../images/linkageMap/6-${this.state.sequecneBkg.sequence6Bkg}.png`} />
                                <img src={`../images/linkageMap/7-${this.state.sequecneBkg.sequence7Bkg}.png`} />
                                <img src={`../images/linkageMap/8-${this.state.sequecneBkg.sequence8Bkg}-2.png`} />
                                <img src={`../images/linkageMap/9-${this.state.sequecneBkg.sequence9Bkg}.png`} />
                                <img src={`../images/linkageMap/l-${this.state.sequecneBkg.sequenceLogisticsBkg}.png`} />
                                <img src={`../images/linkageMap/IOT.png`} />
                                <img src={`../images/linkageMap/tracing.png`} />
                                <img src={`../images/linkageMap/EIMS.png`} />
                                {/*<div className="agv" style={{color: this.state.agvColor}}>磁导AGV</div>
                                <div className="robot" style={{color: this.state.robotColor}}>工业机器人</div>*/}
                            </div>
                        </div>

                        <div className="content-center-important">
                            <div className="important-title">电机健康状态预测</div>
                            <div className="important-up">
                                <div className="flex-center">
                                    <img src="../images/data-before2.png"/>
                                </div>
                                <div className="important-arrow flex-center">
                                    <img src="../images/data-arrow.png"/>
                                </div>
                                <div className="flex-center">
                                    <img src="../images/data-after2.png"/>
                                </div>
                                <div style={{width: '40%'}}>
                                    <img src="../images/data-explain.png"/>
                                </div>
                            </div>
                            <div className="important-down flex-row-between">
                                <div className="important-forecast" ref="forecast"></div>
                                <div className="machine-parameter" ref='machineParameter'></div>
                            </div>
                        </div>
                    </div>
                    <div className="content-right">
                        <div className="content-right-yieldActPressure">
                            <div ref='yield' className="yield"></div>
                            <div ref='activation' className="activation"></div>
                            <div ref='pressure' className="pressure"></div>
                        </div>
                        <div className="right-center">
                            <div className="content-right-yieldActivation" ref="yieldActTrend"></div>
                            <div className="content-right-outputNoise">
                                <div className="output">今日产量：<span>{this.state.todayOutput}</span></div>
                            </div>
                            <div className="content-right-outputTrend" ref="outputTrend"></div>
                        </div>

                        <div className="content-right-IOT flex-column-center">
                            <div className="right-IOT-1">云化生产应用</div>
                            <div className="right-IOT-2">
                                <img src={`../images/IOT-y-${this.state.IOT1ToWebApi}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT1ToService}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT1ToWinApi}.png`}/>
                            </div>
                            <div className="right-IOT-3">
                                <div className="flex-column-center">WEBAPI</div>
                                <div className="flex-column-center">WEBSERVICE</div>
                                <div className="flex-column-center">WINAPI</div>
                            </div>
                            <div className="right-IOT-4 right-IOT-2">
                                <img src={`../images/IOT-y-${this.state.IOT5ToWebApi}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT5ToService}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT5ToWinApi}.png`}/>
                            </div>
                            <div className="right-IOT-5">Integration Component</div>
                            <div className="right-IOT-6">
                                <img src={`../images/IOT-y-${this.state.IOT5ToIOT7}.png`}/>
                            </div>
                            <div className="right-IOT-7">
                                <div className="flex-row-center">SCADA Server</div>
                                <div className="flex-row-center opc-client">OPC Client</div>
                            </div>
                            <div className="right-IOT-8">
                                <img src={`../images/IOT-y-${this.state.IOT7ToIOT9}.png`}/>
                            </div>
                            <div className="right-IOT-9">OPC Server</div>
                            <div className="right-IOT-10">
                                <img src={`../images/IOT-y-${this.state.IOT9To1}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT9To2}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT9To3}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT9To4}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT9To5}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT9To6}.png`}/>
                            </div>
                            <div className="right-IOT-11">
                                <img src={`../images/material.png`}/>
                                <img src={`../images/supply.png`}/>
                                <img src={`../images/marking.png`}/>
                                <img src={`../images/product.png`}/>
                                <img src={`../images/laying-off.png`}/>
                                <img src={`../images/check.png`}/>
                            </div>
                            <div className="IOT-guide">
                                <div><i className="IOT-normal"></i>连接正常</div>
                                <div><i className="IOT-err"></i>连接异常</div>
                            </div>
                            <div id="right-title">设备上云</div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

export default App